<template>
  <div class="app-container" style="padding:15px;">

    <el-form ref="queryFrom" :inline="true" :model="queryFrom" class="demo-form-inline">
      <el-form-item prop="code">
        <el-input v-model="queryFrom.code" placeholder="角色编码" class="el-input--mini" />
      </el-form-item>
      <el-form-item prop="name">
        <el-input v-model="queryFrom.name" placeholder="角色名" class="el-input--mini" />
      </el-form-item>
      <el-form-item prop="status">
        <el-select v-model="queryFrom.status" clearable placeholder="状态" class="el-input--mini">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select></el-form-item>
      <el-form-item>
        <el-button type="primary" class="el-button--mini" icon="el-icon-search" @click="fetchData">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="el-button--mini" icon="el-icon-delete" @click="onReset('queryFrom')">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="el-button--mini" icon="el-icon-user" @click="onAddRole">新增角色</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      text-align="center"
      highlight-current-row
      stripe
      :row-style="{height:'10px'}"
      :cell-style="{padding:'0px'}"
    >
      <el-table-column prop="id" label="ID" width="70px" sortable />
      <el-table-column prop="code" align="center" label="角色CODE" width="180px" />
      <el-table-column prop="name" align="center" label="角色名称" width="180px" />
      <el-table-column prop="status" align="center" label="角色状态" width="180px">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusTagFilter">
            {{ scope.row.status | statusfilters }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" align="center" label="创建时间" width="210px" sortable>
        <template slot-scope="scope">
          <p>{{ scope.row.createdTime | timefilters }}</p>
        </template>
      </el-table-column>
      <el-table-column prop="updatedTime" align="center" label="修改时间" width="210px" sortable>
        <template slot-scope="scope">
          <p>{{ scope.row.updatedTime | timefilters }}</p>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="操作" align="center">
        <template slot-scope="scope">
          <div>
            <el-button type="primary" size="small" class="el-button--mini" icon="el-icon-edit" @click="onEdit(scope.row)">编辑</el-button>
            <el-button :type="scope.row.status | editStatusTagFilter" size="small" class="el-button--mini" icon="el-icon-close" @click="forbiddenUser(scope.row)">{{ scope.row.status ==1? '禁用':'启用' }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-divider />
    <div class="block">
      <el-pagination
        :total="page.totalCount"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      v-loading="dialogLoading"
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      element-loading-text="拼命加载中"
      :close-on-click-modal="false"
      :before-close="closeDialog"
      :show-close="false"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="rules"
      >
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="editForm.name" autocomplete="off" maxlength="21" class="el-input--medium" />
        </el-form-item>
        <el-form-item label="角色CODE" :label-width="formLabelWidth" prop="code">
          <el-input v-model="editForm.code" autocomplete="off" maxlength="21" class="el-input--medium" />
        </el-form-item>
        <el-form-item label="角色状态" :label-width="formLabelWidth" prop="status">
          <el-select v-model="editForm.status" name="editSex" placeholder="角色状态" clearable class="el-input--medium">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择可用菜单" :label-width="formLabelWidth" prop="resourceList">
          <el-tree
            ref="tree"
            v-model="editForm.resourceList"
            :data="treeData"
            show-checkbox
            node-key="id"
            :props="defaultProps"
            default-expand-all
            check-on-click-node
            :highlight-current="true"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="el-button--mini" @click="cancelChange('editForm')">取 消</el-button>
        <el-button class="el-button--mini" type="primary" @click="onSubmitRole('editForm')">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { queryAuthRoleAll, updateAuthRole, queryAllAuthorityMenu, getAuthRoleById, updateAuthRoleOfResource, addAuthRole } from '@/api/system/role'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    timefilters(val) {
      if (val == null || val === '') {
        return '暂无时间'
      } else {
        const d = new Date(val) // val 为表格内取到的后台时间
        const month =
          d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1
        const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate()
        const hours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours()
        const min = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes()
        const sec = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds()
        const times = d.getFullYear() + '-' + month + '-' + day + ' ' + hours + ':' + min + ':' + sec
        return times
      }
    },
    statusfilters(val) {
      if (val == null || val === '') {
        return '--'
      } else {
        if (val === 1) {
          return '正常'
        }
        if (val === 9) {
          return '禁用'
        }
        if (val === 3) {
          return '删除'
        }
        if (val === 4) {
          return '非法'
        }
      }
    },
    statusTagFilter(val) {
      const statusMap = {
        '1': 'success',
        '2': 'info',
        '3': 'danger',
        '4': 'danger'
      }
      return statusMap[val]
    },
    editStatusTagFilter(val) {
      const statusMap = {
        '1': 'warning',
        '9': 'success'
      }
      return statusMap[val]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      dialogFormVisible: false,
      formLabelWidth: '100px',
      dialogTitle: '新增角色',
      options: [{
        value: 1,
        label: '正常'
      }, {
        value: 9,
        label: '禁用'
      }],

      queryFrom: {
        name: '',
        status: '',
        code: ''
      },
      editForm: {
        id: '',
        name: '',
        status: '',
        code: '',
        resourceList: []

      },
      page: {
        'rowCount': 10,
        'currentPage': 1,
        'pageSize': 10,
        'pageCount': 2,
        'totalCount': 0,
        'orderBy': null,
        'outofBounds': false,
        'limitStart': 0
      },
      rules: {
        name: [{ required: true, message: '请填写角色名称', trigger: 'blur' }],
        code: [{ required: true, message: '请填写角色code', trigger: 'blur' }],
        status: [{ required: true, message: '请选择角色状态', trigger: 'blur' }]
        // resourceList: [{ required: true, message: '请选中可用菜单', trigger: 'blur' }]
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      treeData: [],
      defaultCheckedKeys: [],
      dialogLoading: true,
      isAddRole: false
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      var query = { 'page': this.page.currentPage, 'limit': this.page.pageSize }
      var qq = Object.assign(query, this.queryFrom)
      queryAuthRoleAll(qq).then(response => {
        this.list = response.data.list
        this.page = response.data.page
        setTimeout(() => {
          this.listLoading = false
        }, 500)
        this.$notify({ title: response.msg, duration: 1000, type: 'success' })
      })
    },
    onAddRole() {
      this.clearForm()
      this.dialogTitle = '新增角色'
      this.dialogFormVisible = true
      this.isAddRole = true
      queryAllAuthorityMenu().then(response => {
        const menu = response.data
        menu.forEach((p) => {
          const children = []
          if (p.parentId === -1) {
            if (p.children != null && p.children.length > 0) {
              const item = p.children
              item.forEach((it) => {
                children.push({
                  id: it.id,
                  name: it.name,
                  children: it.children,
                  disabled: it.status === 9
                })
              })

              this.treeData.push({
                id: p.id,
                name: p.name,
                children: children,
                disabled: p.status === 9

              })
            }
          }
        })
      })
      this.dialogLoading = false
    },
    onEdit(row) {
      this.clearForm()
      this.dialogTitle = '编辑角色'
      this.isAddRole = false
      this.editForm.name = row.name
      this.editForm.code = row.code
      this.editForm.status = row.status
      this.editForm.id = row.id
      queryAllAuthorityMenu().then(response => {
        const menu = response.data
        menu.forEach((p) => {
          const children = []
          if (p.parentId === -1) {
            if (p.children != null && p.children.length > 0) {
              const item = p.children
              item.forEach((it) => {
                children.push({
                  id: it.id,
                  name: it.name,
                  children: it.children,
                  disabled: it.status === 9
                })
              })

              this.treeData.push({
                id: p.id,
                name: p.name,
                children: children,
                disabled: p.status === 9

              })
            }
          }
        })
      })

      getAuthRoleById({ 'id': row.id }).then(response => {
        const resourceIds = response.data.roleResourceIds
        resourceIds.forEach((p, index) => {
          this.defaultCheckedKeys.push(p)
        })
        // this.defaultCheckedKeys.push(response.data.role.roleResourceIds)
        this.checkStrictly = true // 重点：给数节点赋值之前 先设置为true
        this.$nextTick(() => {
        // 因为我是根据数据id来判断选中所以使用setCheckedKeys，具体可以查看element官网api
          this.$refs.tree.setCheckedKeys(this.defaultCheckedKeys) // 给树节点赋值
          this.checkStrictly = false // 重点： 赋值完成后 设置为false
        })
      })
      this.dialogFormVisible = true
      this.dialogLoading = false
    },
    onSubmitRole(formName) {
      this.$refs[formName].validate((valida) => {
        if (valida) {
          const checkedNodes = this.$refs.tree.getCheckedNodes().concat(this.$refs.tree.getHalfCheckedNodes()) // this.$refs.tree.getCheckedNodes()
          checkedNodes.forEach((p) => {
            this.editForm.resourceList.push({
              value: p.id,
              title: p.name,
              checked: true,
              disabled: false
            })
          })
          if (!this.isAddRole) {
            updateAuthRoleOfResource(this.editForm).then(response => {
              // this.$notify({ title: response.msg, duration: 1000, type: 'success' })
              this.fetchData()
              this.clearForm()
            })
          } else {
            addAuthRole(this.editForm).then(response => {
              // this.$notify({ title: response.msg, duration: 1000, type: 'success' })
              this.fetchData()
              this.clearForm()
            })
          }
        } else {
          return false
        }
        // console.log(this.editForm)
        this.$refs[formName].clearValidate()
      })
    },
    forbiddenUser(row) {
      this.editForm.id = row.id
      this.editForm.name = row.name
      this.editForm.status = row.status === 1 ? 9 : 1
      this.editForm.code = row.code
      this.editForm.resourceList = []
      const title = row.status === 1 ? '禁用' : '启用'
      this.$confirm('确认要' + title + '该角色: ' + row.name + ' 吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateAuthRole(this.editForm).then(response => {
          this.$notify({ title: response.msg, duration: 1000, type: 'success' })
          this.fetchData()
          this.clearForm()
        })
      }).catch(() => {
      })
    },
    onReset(formName) {
      this.$refs[formName].resetFields()
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.fetchData()
    },
    closeDialog() {
      this.cancelChange()
    },
    cancelChange(formName) {
      this.dialogFormVisible = false
      this.clearForm()
      this.$refs[formName].clearValidate()
    },
    clearForm() {
      this.editForm.name = ''
      this.editForm.code = ''
      this.editForm.status = ''
      this.editForm.id = ''
      this.editForm.resourceList = []
      this.treeData = []
      this.defaultCheckedKeys = []
      this.dialogLoading = true
      this.dialogFormVisible = false
    }
  }
}
</script>
